package com.jeesite.modules.exam.score.web;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.annotation.RepeatSubmit;
import com.jeesite.modules.common.dao.SysBasicDao;
import com.jeesite.modules.common.service.SysOfficeUnitService;
import com.jeesite.modules.exam.assessment.entity.DcSupExamInfo;
import com.jeesite.modules.exam.notice.service.DcSupExamNoticeService;
import com.jeesite.modules.exam.quota.entity.DcSupExamSumQuotaInfo;
import com.jeesite.modules.exam.quota.service.DcSupExamSumQuotaOrgService;
import com.jeesite.modules.exam.score.entity.DcSUpExamDxExport;
import com.jeesite.modules.exam.score.entity.DcSupExamScore;
import com.jeesite.modules.exam.score.entity.DcSupExamSumScore;
import com.jeesite.modules.exam.score.service.DcSupExamScoreService;
import com.jeesite.modules.exam.score.vo.DcSupExamQuotaOrgVo;
import com.jeesite.modules.exam.score.vo.DcSupExamVo;
import com.jeesite.modules.home.entity.cuibanDto;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.utils.DictUtils;
import com.jeesite.modules.sys.utils.UserUtils;

import com.jeesite.modules.task.action.dao.DcSupTaskActionDao;
import com.jeesite.modules.task.deploy.entity.OfficeUser;
import com.jeesite.modules.utils.OfficeUtil;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 单项指标评分
 */
@Controller
@RequestMapping("${adminPath}/score/dcSupExamDXZBScore")
@RequiredArgsConstructor
public class DcSupExamDXZBScoreController extends BaseController {

    private final DcSupExamNoticeService dcSupExamNoticeService;

    private final DcSupExamScoreService dcSupExamScoreService;

    private final DcSupExamSumQuotaOrgService dcSupExamSumQuotaOrgService;

    private final SysOfficeUnitService sysOfficeUnitService;

    private final SysBasicDao sysBasicDao;

    private final DcSupTaskActionDao dcSupTaskActionDao;


    /**
     * 单项指标页面
     */
    @RequiresPermissions("score:dcSupDxScore:view")
    @RequestMapping("view")
    public String indexView(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo,String noticeId, Model model){
        model.addAttribute("dcSupExamSumQuotaInfo",dcSupExamSumQuotaInfo);
        DcSupExamVo dcSupExamVo = new DcSupExamVo();
        DcSupExamScore dcSupExamScoreVo = new DcSupExamScore();
        dcSupExamScoreVo.setExamId(dcSupExamSumQuotaInfo.getExamId());
        dcSupExamScoreVo.setNoticeId(noticeId);
        dcSupExamScoreVo.setScoreType("3");
        dcSupExamScoreVo.setScoreOrg(sysOfficeUnitService.getLatestUnitByOffice().getOfficeCode());
        DcSupExamScore dcSupExamScore = dcSupExamScoreService.findDcSupExamScore(dcSupExamScoreVo);
        dcSupExamVo.setDcSupExamScore(Optional.ofNullable(dcSupExamScore).orElseGet(DcSupExamScore::new));
        dcSupExamVo.setDcSupExamNotice(dcSupExamNoticeService.get(noticeId));
        model.addAttribute("dcSupExamVo",dcSupExamVo);//查询指标是否都确认过分数
        return "modules/exam/score/dcSupExamDXZBScore";
    }



    @RequestMapping("dxOnlyReadView")
    public String dxOnlyReadView(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo,String noticeId, Model model){
        model.addAttribute("dcSupExamSumQuotaInfo",dcSupExamSumQuotaInfo);
        DcSupExamVo dcSupExamVo = new DcSupExamVo();
        DcSupExamScore dcSupExamScoreVo = new DcSupExamScore();
        dcSupExamScoreVo.setExamId(dcSupExamSumQuotaInfo.getExamId());
        dcSupExamScoreVo.setNoticeId(noticeId);
        dcSupExamScoreVo.setScoreType("3");
        dcSupExamScoreVo.setScoreOrg(dcSupExamSumQuotaInfo.getGradeOrg());
        DcSupExamScore dcSupExamScore = dcSupExamScoreService.findDcSupExamScore(dcSupExamScoreVo);
        dcSupExamVo.setDcSupExamScore(Optional.ofNullable(dcSupExamScore).orElseGet(DcSupExamScore::new));
        dcSupExamVo.setDcSupExamNotice(dcSupExamNoticeService.get(noticeId));
        model.addAttribute("dcSupExamVo",dcSupExamVo);//查询指标是否都确认过分数
        model.addAttribute("gradeOrg",dcSupExamSumQuotaInfo.getGradeOrg());//查询指标是否都确认过分数
        return "modules/exam/score/dcSupExamDXZBScoreOnlyRead";
    }

    /**
     * 退回评分单位状态到未提交状态
     */
    @ResponseBody
    @PostMapping("dxWithdraw")
    public String dxWithdraw(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo){
        DcSupExamScore dcSupExamScore = new DcSupExamScore();
        dcSupExamScore.setExamId(dcSupExamSumQuotaInfo.getExamId());
        dcSupExamScore.setScoreType("9");
        DcSupExamScore dcSupExamScore1 = dcSupExamScoreService.findDcSupExamScore(dcSupExamScore);
        if(dcSupExamScore1!=null){
            return renderResult(Global.FALSE, text("退回失败,只有评分汇总所有单位【已提交前状态】可退回"));
        }
        int update = dcSupExamScoreService.dxWithdraw(dcSupExamSumQuotaInfo);
        if(update>0){
            return renderResult(Global.TRUE, text("退回成功"));
        }
        return renderResult(Global.FALSE, text("退回失败"));
    }


    /**
     * 获取单项指标数据
     * @param dcSupExamSumQuotaInfo
     * @param response
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("findDXListData")
    public Page<DcSupExamSumQuotaInfo> findDXListData(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo, HttpServletResponse response, HttpServletRequest request){
        dcSupExamSumQuotaInfo.setPage(new Page<>(request,response));
        Page<DcSupExamSumQuotaInfo> dxListData = dcSupExamScoreService.findDXListDataPage(dcSupExamSumQuotaInfo);
        return dxListData;
    }

    /**
     * 获取单位对应评分数据
     */
    @ResponseBody
    @PostMapping("findUnitScoreListData")
    public Map<String, Object> findUnitScoreListData(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo){
        Map<String, Object> unitScoreListData = dcSupExamScoreService.findUnitScoreListData(dcSupExamSumQuotaInfo);
        return unitScoreListData;
    }

    /**
     * 保存单项指标分数 并且添加草稿状态汇总
     */
    @RequiresPermissions("score:dcSupDxScore:view")
    @PostMapping("/saveDXScore")
    @ResponseBody
    public String saveDXScore(DcSupExamVo dcSupExamVo){
        if (UserUtils.getUser().getUserCode().equals("system")) {
            return renderResult(Global.FALSE,"操作禁止！");
        }
        dcSupExamScoreService.saveDXScore(dcSupExamVo);
        return renderResult(Global.TRUE,"保存成功！");
    }

    /**
     * 提交单项指标分数
     * @param dcSupExamVo
     * @return
     */
    @RequiresPermissions("score:dcSupDxScore:view")
    @PostMapping("/subDXScore")
    @ResponseBody
    public String subDXScore(DcSupExamVo dcSupExamVo){
        if (UserUtils.getUser().getUserCode().equals("system")) {
            return renderResult(Global.FALSE,"操作禁止！");
        }
        dcSupExamScoreService.subDXScore(dcSupExamVo);
        return renderResult(Global.TRUE,"保存成功！");
    }

    /**
     * 导出
     */
    @GetMapping("/exportDxScore")
    public void exportDxScore(DcSupExamScore dcSupExamScore,HttpServletResponse response) throws Exception {
        List<DcSUpExamDxExport> list = dcSupExamScoreService.exportDxScore(dcSupExamScore);
        Map<String, List<DcSUpExamDxExport>> mapData = list.stream().collect(Collectors.groupingBy(DcSUpExamDxExport::getCustomSort));
        ArrayList<DcSUpExamDxExport> dcSUpExamDxExports = ListUtils.newArrayList();
        Set<String> CustomSorts = mapData.keySet().stream().sorted((o1, o2) -> Integer.valueOf(o1).compareTo(Integer.valueOf(o2))).collect(Collectors.toCollection(LinkedHashSet::new));
        for (String CustomSort : CustomSorts) {
            List<DcSUpExamDxExport> dcSUpExamDxExportByNum = mapData.get(CustomSort);
            if (dcSUpExamDxExportByNum.size()>1){
                dcSUpExamDxExportByNum.stream().skip(1).forEach(x->x.setCustomSort(""));
            }
            dcSUpExamDxExports.addAll(dcSUpExamDxExportByNum);
        }
        for (DcSUpExamDxExport dcSUpExamDxExport : dcSUpExamDxExports) {
            //处理字典
            String code = dcSUpExamDxExport.getQuotaType();
            dcSUpExamDxExport.setQuotaType(DictUtils.getDictLabel("dc_quotaType", code, ""));

            String assessMethod = dcSUpExamDxExport.getAssessMethod();
            dcSUpExamDxExport.setAssessMethod(DictUtils.getDictLabel("dc_exam_assessment",assessMethod,""));
            //处理显示格式
            if (StringUtils.isNotBlank(dcSUpExamDxExport.getPercentage())){
                dcSUpExamDxExport.setPercentage(dcSUpExamDxExport.getPercentage()+"%");
            }else {
                dcSUpExamDxExport.setPercentage("0.00%");
            }
        }
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("quotaType","类别");
        writer.setColumnWidth(0,15);
        writer.addHeaderAlias("customSort","序号");
        writer.addHeaderAlias("assessMethod","考核方式");
        writer.addHeaderAlias("quotaContent","目标内容");
        writer.setColumnWidth(3,40);
        writer.addHeaderAlias("exameOrgName","被考核单位");
        writer.setColumnWidth(4,35);
        writer.addHeaderAlias("quotaWeight","权数");
        writer.addHeaderAlias("currentYaerGoal","本年度目标");
        writer.addHeaderAlias("percentage","百分制得分");
        writer.addHeaderAlias("quotaScore","得分");
        writer.addHeaderAlias("scoreReason","备注");
        writer.setColumnWidth(9,35);
        writer.addHeaderAlias("ranking","排名");
        writer.write(dcSUpExamDxExports,true);


        //设置content—type
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");
        //设置标题
        String fileName= URLEncoder.encode("单项指标评分"+DateUtils.formatDate(new Date(),"yyyyMMdd"),"UTF-8");
        //Content-disposition是MIME协议的扩展，MIME协议指示MIME用户代理如何显示附加的文件。
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        ServletOutputStream outputStream= response.getOutputStream();

        //将Writer刷新到OutPut
        writer.flush(outputStream,true);
        outputStream.close();
        writer.close();
    }


    /**
     * 获取单项指标未评分的牵头评分单位
     * @return
     */
    @GetMapping("/getNoScoreGradeOrg")
    @ResponseBody
    public List<Map<String, String>> getNoScoreGradeOrg(String examId, String examOrg){
        List<Map<String,String>> result=dcSupExamScoreService.getNoScoreGradeOrg(examId,examOrg);
        return result;
    }

    @RequestMapping(value = "cuiban")
    @ResponseBody
    public String cuiban(DcSupExamSumScore dcSupExamSumScore) {
        dcSupExamScoreService.cuiban(dcSupExamSumScore);
        return renderResult(Global.TRUE, text("催办成功！"));
    }


    @RequestMapping(value = "readListView")
    public String readListView(DcSupExamInfo dcSupExamInfo, Model model){
        model.addAttribute("dcSupExamInfo", dcSupExamInfo);
        Integer currentYear = Integer.parseInt(DateUtils.getYear());
        model.addAttribute("yearList", OfficeUtil.getYearList(currentYear));
        model.addAttribute("currentYear", currentYear);
        return "modules/exam/score/dcSupExamReadScoreList";
    }

    /**
     * 单项指标查询页
     * @param dcSupExamInfo
     * @param model
     * @return
     */
    @RequestMapping(value = "readDXListView")
    public String readDXListView(DcSupExamInfo dcSupExamInfo, Model model){
        model.addAttribute("dcSupExamInfo", dcSupExamInfo);
        Integer currentYear = Integer.parseInt(DateUtils.getYear());
        model.addAttribute("yearList", OfficeUtil.getYearList(currentYear));
        model.addAttribute("currentYear", currentYear);
        return "modules/exam/score/dcSupExamReadDXScore";
    }

    /**
     * 查询各评分单位进度查询
     * @return Str
     */
    @RequestMapping(value = "dxScoreStepInfo")
    @ResponseBody
    public List<DcSupExamQuotaOrgVo> dxScoreStepInfo(@RequestParam("id") String examId,@RequestParam(value = "gradeOrgName",required = false) String gradeOrgName){
       List<DcSupExamQuotaOrgVo> list = dcSupExamScoreService.dxScoreStepInfo(examId);
       if (StringUtils.isNotBlank(gradeOrgName)){
           list=list.stream().filter(x->x.getGradeOrgName().contains(gradeOrgName)).collect(Collectors.toList());
       }
        return list;
    }

    @RequestMapping(value = {"cuibanPageDXCK", ""})
    public String cuibanPageDX(cuibanDto cuiban , Model model) {
        // 定义催办的初始文本
        cuiban.setMessage("您有一个单项指标评分被催办,请及时查看");
        // 定义临时变量
        String tempUserCode = "";
        String tempUserName = "";
        List<Map<String, String>> listUser = new ArrayList<>();

        // 获取考核单位角色
        List<OfficeUser> userByOrg = dcSupTaskActionDao.getUserByOrg("EL_ORG", cuiban.getOrg());
        if (userByOrg != null && userByOrg.size() > 0) {
            // 遍历集合，设置页面初始值
            for (int i = 0; i < userByOrg.size(); i++) {
                User transferUser = UserUtils.get(userByOrg.get(i).getUserCode());
                Map<String, String> map = new HashMap<>();
                map.put("name", transferUser.getUserName());
                map.put("userCode", transferUser.getUserCode());
                map.put("phone", transferUser.getMobile());
                map.put("id", transferUser.getUserCode());
                listUser.add(map);
                tempUserCode = tempUserCode + "," + transferUser.getUserCode();
                tempUserName = tempUserName + "," + transferUser.getUserName();
            }
            // 过滤字符串第一个逗号
            tempUserCode = tempUserCode.substring(1);
            tempUserName = tempUserName.substring(1);
        }

        model.addAttribute("defaultUserList", listUser);
        cuiban.setUserCode(tempUserCode);
        cuiban.setName(tempUserName);
        model.addAttribute("cuibanPage", cuiban);
        model.addAttribute("orgCode", cuiban.getOrg());
        return "modules/exam/score/cuibanPageDXCK";
    }


    /**
     * 单项指标审核催办
     * @param cuiban
     * @return
     */
    @RequestMapping(value = "cuibanDXCK")
    @ResponseBody
    @RepeatSubmit
    public String cuibanDXCK(cuibanDto cuiban) {
        dcSupExamScoreService.cuibanDXCK(cuiban);
        return renderResult(Global.TRUE, text("催办成功!"));
    }


    /**
     *
     * 单项指标评分分数修改
     * @return
     */
    @RequestMapping(value = "updateScoreInfo")
    @ResponseBody
    @RepeatSubmit
    public String updateScoreInfo(DcSupExamSumScore score) {
        try {
            dcSupExamScoreService.updateScoreInfo(score);
        } catch (Exception e) {
            return renderResult(Global.FALSE, text(e.getMessage()));
        }
        return renderResult(Global.TRUE, text("修改成功!"));
    }
}
